<!DOCTYPE html>
<html lang="zh-en">
<head>
  <meta charset="UTF-8">
  <title>优化 DOM 操作</title>
</head>
<body>
<!-- http://huziketang.mangojuice.top/books/react/lesson3 -->

<div class="wrap"></div>

<script>
  class LikeBtn {
    constructor() {
      this.state = {
        is_liked: false
      }
      this.num = 0
    }

    createDom(domString) { // 把字符串模板转化成 DOM元素
      let cDiv = document.createElement('div')
      cDiv.innerHTML = domString
      if (cDiv.children.length > 1) throw new Error('组件需要在同一个元素中')

      let dom = cDiv.children[0]
      document.body.appendChild(cDiv)
      document.body.removeChild(cDiv)

      return dom
    }

    setState(state) {
      let oldEl = this.el
      this.state = state
      this.el = this.render()
      if (this.onStateChange) {
        this.onStateChange(oldEl, this.el)
      }
    }

    changeBtnTxt() {
      this.setState({
        is_liked: !this.state.is_liked
      })
    }

    render() {
      this.el = this.createDom(`
                <button class="btn" data-num="${this.num}">
                    <span class="btn-txt">${this.state.is_liked ? '取消' : '点赞'}</span>
                    <span>👍</span>
                </button>`)
      this.el.addEventListener('click', this.changeBtnTxt.bind(this), false)

      this.num++
      return this.el
    }
    // onStateChange(oldEl, newEl) {
    //   eWrap.insertBefore(newEl, oldEl)
    //   eWrap.removeChild(oldEl)
    // }
  }

  var eWrap = document.querySelector('.wrap')

  var zlikeBtn = new LikeBtn()
  eWrap.appendChild(zlikeBtn.render()) // 生成 btn
  zlikeBtn.onStateChange = (oldEl, newEl) => { // 每次都要重新设置 onStateChange
    // console.log(eWrap);
    // console.log(oldEl);
    // console.log(newEl);
    console.log(2);
    eWrap.insertBefore(newEl, oldEl)
    eWrap.removeChild(oldEl)
  }

  var zlikeBtn2 = new LikeBtn()
  eWrap.appendChild(zlikeBtn2.render())
  zlikeBtn.onStateChange = (oldEl, newEl) => { // 每次都要重新设置 onStateChange
    eWrap.insertBefore(newEl, oldEl)
    eWrap.removeChild(oldEl)
  }

</script>
</body>

</html>